package com.bestattempt.utility.bind.initializers.hibernateImpl;

import com.bestattempt.utility.bind.InitializerException;
import com.bestattempt.utility.bind.initializers.defaultImpl.ListInitializer;
import static com.bestattempt.utility.reflection.ReflectionUtil.getFieldValue;
import org.hibernate.collection.PersistentList;

import java.lang.reflect.Field;
import java.util.List;

/**
 * TODO: Document me
 *
 * @author Ganeshji Marwaha
 * @since Nov 4, 2006
 */
public class HibernateListInitializer extends ListInitializer {

    public Object initialize(Object object, Field field, String index) {
        List list = (List) getFieldValue(object, field);
        log.debug("HibernateListInitializer is taking over the task of initializing the list: " + field.getName());

        if (list instanceof PersistentList) {
            log.debug("Hibernate PersistentList found. Checking if it was initialized or not.");
            if( !((PersistentList) list).wasInitialized() ) {
                log.debug("Hibernate PersistentList was not initialized. Not proceeding with list initialization.");
                throw new InitializerException("List was not initialized by the ORM");
            }
        }

        log.debug("Hibernate PersistentList was initialized. Proceeding with default list initialization");
        return super.initialize(object, field, index);
    }

}
